package org.homly.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.homly.model.Order;
import org.homly.sql.SQLTool;

public class OrderService {

	@SuppressWarnings("unchecked")
	public static List<HashMap<String, String>> getOrders(HashMap para) throws Exception {

		List<HashMap<String, String>> orders = null;

		Short status = (Short) para.get("status");

		StringBuffer sqlSB = new StringBuffer();
		sqlSB.append(" SELECT * FROM `order`");

		if (status != null && "0".equals(status)) {
			sqlSB.append(" WHERE order_status=0");
		} else if (status != null && "1".equals(status)) {
			sqlSB.append(" WHERE order_status=1");
		}

		sqlSB.append(" ORDER BY order_id DESC");
		try {
			orders = SQLTool.query(sqlSB.toString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return orders;
	}

	@SuppressWarnings("unchecked")
	public static HashMap<String, String> getOrder(HashMap para) throws Exception {

		HashMap<String, String> order = null;

		Integer id = (Integer) para.get("id");

		StringBuffer sqlSB = new StringBuffer();
		sqlSB.append(" SELECT * FROM `order`");

		if (id != null) {
			sqlSB.append(" WHERE order_id=").append(id);
		}

		sqlSB.append(" LIMIT 1");
		try {
			List<HashMap<String, String>> orders = null;
			orders = SQLTool.query(sqlSB.toString());
			if (orders != null && orders.size() > 0) {
				order = orders.get(0);
			} else {
				order = new HashMap();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return order;
	}

	public static void updateOrder(Order order) throws Exception {

		String sql = " UPDATE `order` SET order_note=?,order_status=?,order_modify_time=? WHERE order_id=?";
		Object[] para = {order.getOrderNote(), order.getOrderStatus(),
				new Date(), order.getOrderId()};

		SQLTool.update(sql, para);
	}

	public static List<HashMap<String, String>> getOrderDetailsByOrderId(
			Integer orderId) {

		List<HashMap<String, String>> orderDetails = null;

		String sql = " SELECT * FROM order_detail WHERE order_id=" + orderId;
		try {
			orderDetails = SQLTool.query(sql);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			orderDetails = new ArrayList<HashMap<String, String>>();
		}

		return orderDetails;
	}
}
